package com.lft.examsys.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lft.examsys.entity.Paper;
import com.lft.examsys.mapper.ItemMapper;
import com.lft.examsys.mapper.PaperMapper;
import com.lft.examsys.model.IModel;
import com.lft.examsys.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Qingchen
 * @date ：Created in 2022/4/2 10:59
 * @description：paper服务层
 * @modified By：
 * @version: $
 */
@Service
public class PaperService {

    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private ItemMapper itemMapper;

    public Page<Paper> getAllByPage(IModel model, Integer page, Integer size, String elName) {
        return PageUtil.getAllByPage(model,page,size, paperMapper, elName);
    }

    public Page<Paper> getAllOrderByTime(Page<Paper> page) {
        return paperMapper.getAllOrderByTime(page);
    }

    //          paper_id items
    public Map<Object, Object> getPaperCount() {
        List<Map<String, Integer>> res = paperMapper.selectPaperCount();
        Map<Object, Object> result = new HashMap<>();
        for (Map re : res) {
            result.put(re.get("paperId"), re.get("items"));
        }
        return result;
    }

    public Paper getPaperById(Integer id) {
        return paperMapper.selectById(id);
    }

    public Boolean deleteItem(Integer paperId, Integer itemId) {
        return paperMapper.deleteItemId(paperId, itemId);
    }

    public Integer savePaper(Paper paper) {
        return paperMapper.insert(paper);
    }

    public Boolean insertPaperItem(Integer itemId, Integer paperId) {
        return paperMapper.insertPaperItem(itemId, paperId);
    }

    public Integer getMaxId() {
        return paperMapper.selectMaxId();
    }

    public Integer deletePaper(Integer id) {
        itemMapper.deleteItemsByPaperId(id); // 删除中间表信息
        return paperMapper.deleteById(id);
    }

    public Boolean insertScore(Integer userId, Integer paperId, Date time, Integer score) {
        return paperMapper.insertScore(userId,paperId,time,score);
    }

    public Integer existExam(Integer paperId, Integer userId) {
        return paperMapper.selectUserIfExistExam(paperId, userId);
    }

    public Integer updatePaper(Paper paper) {
        return paperMapper.updateById(paper);
    }

    public List<Paper> getPapers() {
        return paperMapper.selectPapers();
    }

}
